<?php
namespace app\admin\controller;

use app\admin\controller\Base;
use think\Db;
use think\Request;

class Account extends Base
{

    /**
     * 账户列表 user_type  0管理员 2院长 1教师
     */
    public function list()
    {
        $page  = request()->param('page', '1');
        $limit = request()->param('limit', 10);
        $keyword = request()->param('keywords', '');
        $user_type = request()->param('user_type', '0');
        // 总数
        $where = [];
        if ($user_type){
            $where[]=['user_type','=',$user_type];
        }

        if ($keyword){
            $where[]=['realname|user_name','like','%'.$keyword];
        }
        $total = Db::name("Admin")->where($where)->count();
        // 搜索条件

        $list = Db::name("Admin")->where($where)->page($page, $limit)->order("uid desc")->select();
        foreach ($list as $key => $value) {
            $list[$key]['create_time'] = date('Y-m-d H:i', $value['reg_time']);
        }
        $data = [
            'total'  => $total,
            'list'   => $list,
        ];
        return $this->ok($data);
    }


    //添加账号
    public function save()
    {
        $uid=request()->param("uid",'0','intval');
        $data=request()->only(['user_name','user_password','user_type','realname']);
        $data['user_password']=encryptAdminPassword($data['user_password']);


        if (empty($uid)){
            $member=Db::name("Admin")->where(['user_type'=>$data['user_type'],'user_name'=>$data['user_name']])->find();
            if (!empty($member)){
                return $this->fail('该账号已存在');
            }
            $data['reg_time']=time();
            $res=Db::name("Admin")->insert($data);
        }else{
            unset($data['user_name']);
            $res=Db::name("Admin")->where(['uid'=>$uid])->update($data);
        }

        if ($res){
            return $this->ok('操作成功');
        }else{
            return $this->fail('操作失败');
        }

    }


    public function detail()
    {
        $uid=request()->param("uid",'0','intval');
        $detail=Db::name("Admin")->where(['uid'=>$uid])->find();
        return $this->ok($detail);
    }



}
